<template>
  <div class="myTab">
    <!-- 页签导航 -->
    <a-tabs
      v-model:activeKey="activeKey"
      type="editable-card"
      @edit="handleTabClose"
      hide-add
      @tabClick="tabClick"
    >
      <a-tab-pane
        v-for="(tab, index) in tabs"
        :key="tab.path"
        :tab="tab.title"
        :closable="tab.closable"
        @change="handleTabClick(tab)"
      >
      </a-tab-pane>
    </a-tabs>
  </div>
</template>

<script setup>
import { ref, onBeforeMount } from "vue";
import { useRouter } from "vue-router";

const router = useRouter();
const tabs = ref([]); // 存储页签信息的数组
const activeKey = ref(""); // 当前选中的页签

// 在组件初始化时加载当前页签
onBeforeMount(() => {
  tabs.value.push({
      title: '工作台',
      path: '/home',
      name: 'home',
      closable: false,
  });

  const existingTab = tabs.value.find(
    (tab) => tab.name === router.currentRoute.value.name
  );
  if (!existingTab) {
    tabs.value.push({
      title: router.currentRoute.value.meta.title,
      path: router.currentRoute.value.fullPath,
      name: router.currentRoute.value.name,
      closable: true,
    });
    activeKey.value = router.currentRoute.value.fullPath;
  }
});

// 监听路由变化
router.afterEach((to) => {
  // const existingTab = tabs.value.find((tab) => tab.path === to.fullPath);
  const existingTab = tabs.value.find((tab) => tab.name === to.name);
  if (!existingTab) {
    // 如果页签中不存在当前路由，则添加到页签中
    tabs.value.push({
      title: to.meta.title, // 页签标题
      path: to.fullPath, // 路由路径
      name: to.name,
      closable: true, // 是否可关闭
    });
    activeKey.value = to.fullPath; // 设置当前选中页签为新添加的页签
  } else {
    activeKey.value = existingTab.path; // 如果页签已存在，则设置为当前选中页签
  }

  if (tabs.value.length > 1) {
    //如果页签数量大于1，则所有页签的closable为true
    tabs.value.forEach((item) => {
      if(item.title!='工作台'){
        item.closable = true;
      }
    });
  } 
});

// 处理页签点击事件
const handleTabClick = (tab) => {
  router.push(tab.path); // 点击页签时切换路由
};
// 处理页签关闭事件
const handleTabClose = (targetKey) => {
  const tab = tabs.value.find((tab) => tab.path === targetKey);
  if (tab) {
    const index = tabs.value.indexOf(tab);
    tabs.value.splice(index, 1); // 从页签数组中移除关闭的页签
    if (tabs.value.length === 1) {
      tabs.value[0].closable = false;
    }
    if (tabs.value.length === 0) {
      router.push("/"); // 如果关闭的是最后一个页签，则跳转至工作台或其他默认页面
    } else {
      // 如果关闭的是当前选中页签且还有其他页签，则切换至最后一个页签
      if (activeKey.value === targetKey) {
        activeKey.value = tabs.value[tabs.value.length - 1].path;
        router.push(activeKey.value);
      }
    }
  }
};

const tabClick = (e) => {
  router.push(e);
};
</script>

<style scoped lang="scss">
/* 在这里可以添加样式 */
.myTab {
  :deep .ant-tabs-tab {
    font-size: 16px;
    color: #000;
  }
  :deep .ant-tabs-tab-active {
    color: #1890ff;
  }
}
</style>
